#include "confmsg.h"
#include "ui_confmsg.h"
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <iostream>
#include <string>
#include <QProcess>
using namespace std;

ConfMsg::ConfMsg(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ConfMsg)
{
    ui->setupUi(this);
//    QString str = ui->textEdit->toPlainText().trimmed().replace("<","").replace(">","");
//    qDebug() << "xx " << str;

//    qDebug() << str.indexOf("''");
//    QFile file("D:/Test/temp.txt");
//    bool isOk = file.open(QIODevice::WriteOnly);
//    if(!isOk)
//    {
//       return;
//    }
//    QTextStream stream(&file);
//    stream <<str;
//    file.close();
//    QFile f("D:/Test/temp.txt");
//    isOk = f.open(QIODevice::ReadOnly);
//    if(!isOk)
//    {
//        qDebug() << "  " ;
//        return;
//    }
//    QByteArray arr;
//    qDebug() << f.atEnd();
//    QString s;
//    while(!f.atEnd())
//    {
//        s =QString::fromLocal8Bit(f.readLine()).trimmed();
//    }
//    f.close();
//    qDebug() << str.indexOf('\r\n');

}

ConfMsg::~ConfMsg()
{
    delete ui;
}

void ConfMsg::on_buttonFile_clicked()
{
    //判断程序是否打开
    //请求报文
    ui->buttonFile->setEnabled(false);
    QFile reqFile("./request.txt");
    if(reqFile.exists())
    {
        reqFile.remove();
    }
    reqFile.open(QIODevice::WriteOnly);
    reqFile.close();
    //请求报文中文
    QFile reqzh_cnFile("./requestRemark.txt");
    if(reqzh_cnFile.exists())
    {
        reqzh_cnFile.remove();
    }
    reqzh_cnFile.open(QIODevice::WriteOnly);
    reqzh_cnFile.close();

    //响应报文
    QFile respFile("./response.txt");
    if(respFile.exists())
    {
        respFile.remove();
    }
    respFile.open(QIODevice::WriteOnly);
    respFile.close();
    //中文
    QFile respzh_cnFile("./responseRemark.txt");
    if(respzh_cnFile.exists())
    {
        respzh_cnFile.remove();
    }
    respzh_cnFile.open(QIODevice::WriteOnly);
    respzh_cnFile.close();
    QProcess *p = new QProcess(this);
    p->start("tasklist");
    p->waitForFinished();
    QByteArray res =p->readAllStandardOutput();
    if(res.indexOf("notepad++.exe") == -1)
    {
        QStringList list;
        list <<"./responseRemark.txt" << "./response.txt"<< "./requestRemark.txt" <<"./request.txt" ;
        p->start("notepad++.exe",list);

    }
}

void ConfMsg::on_buttonTransform_clicked()
{
    //读取文件
    QString AppID ="E59901";
    QString targetFile = QString("./msg_%1.xml").arg(AppID);
    QString msgID ="99NISPLC0008";
    QString tranCodeName = "理财签约";

    QFile file("./request.txt");
    m_resNum =0;
    QStringList resList,resRemarkList;
    QString strLine;
    bool isOk = file.open(QIODevice::ReadOnly);
    if(!isOk)
    {
        qDebug() << "open file fail";
        return;
    }
    while (!file.atEnd())
    {
        m_resNum +=1;
        qDebug() << "m_resNum " <<m_resNum;
        strLine = file.readLine().trimmed();
        strLine =strLine.replace(" ","").replace("<","").replace(">","");
        resList <<strLine;
        qDebug() <<strLine;

    }
    file.close();
    m_resRemarkNum =0;
    QFile resRemarkFile("./requestRemark.txt");
    if(!resRemarkFile.open(QIODevice::ReadOnly))
    {
        return;
    }
    while (!resRemarkFile.atEnd()) {
        m_resRemarkNum +=1;
        strLine = QString::fromLocal8Bit(resRemarkFile.readLine().trimmed());
        //strLine =strLine.replace(" ","").replace("<","").replace(">","");
        resRemarkList << strLine;
    }

    m_resTagLenMax =0;
    if(m_resNum == m_resRemarkNum && m_resNum !=0 && m_resRemarkNum !=0)
    {
        // request == remark
        for(int i=0; i < m_resNum; i++)
        {
            m_Field.m_strRequestPath = resList.at(i);
            QStringList list = resList.at(i).split("/");
            QString str = list.at(list.length()-1);
            QString strTagName = QString("F_%1_%2").arg(AppID).arg(str);
            m_Field.m_strTagName = strTagName;
            QString strValue = QString("$%1_P_%2").arg(AppID).arg(str);
            m_Field.m_strValue = strValue ;
            m_Field.m_strRemark =resRemarkList.at(i);
            m_FieldGatherList.push_back(m_Field);
            m_resTagLenMax = CompareThreeNum(strValue.length(),strTagName.length(),m_resTagLenMax);
        }
    }

    //response
    QFile respfile("./response.txt");
    m_respNum =0;
    QStringList respList,respRemarkList;
    if(!respfile.open(QIODevice::ReadOnly))
    {
        qDebug() << "open file fail";
        return;
    }
    while (!respfile.atEnd())
    {
        m_respNum +=1;
        strLine = respfile.readLine().trimmed();
        strLine =strLine.replace(" ","").replace("<","").replace(">","");
        respList <<strLine;
        qDebug() <<strLine;

    }
    file.close();
    m_respRemarkNum =0;
    QFile respRemarkFile("./responseRemark.txt");
    if(!respRemarkFile.open(QIODevice::ReadOnly))
    {
        return;
    }
    while (!respRemarkFile.atEnd()) {
        m_respRemarkNum +=1;
        strLine = QString::fromLocal8Bit(respRemarkFile.readLine().trimmed());
        //strLine =strLine.replace(" ","").replace("<","").replace(">","");
        respRemarkList << strLine;
    }
    m_respTagLenMax =0;
    if(m_respNum == m_respRemarkNum && m_respNum !=0 && m_respRemarkNum !=0)
    {
        // response == remark
        for(int i=0; i < m_respNum; i++)
        {
            m_Field.m_strResponsePath = respList.at(i);
            QStringList list = respList.at(i).split("/");
            QString str = list.at(list.length()-1);
            QString strTagName = QString("F_%1_%2").arg(AppID).arg(str);
            m_Field.m_strTagName = strTagName ;
            QString strValue = QString("$%1_RP_%2").arg(AppID).arg(str);
            m_Field.m_strValue = strValue;
            m_Field.m_strRemark =respRemarkList.at(i);
            m_FieldGatherList.push_back(m_Field);
            m_respTagLenMax = CompareThreeNum(strValue.length(),strTagName.length(),m_respTagLenMax);
        }
    }
    qDebug() << "xml transform .";
    //写xml
    QChar space =QChar(' ');
    QFile newFile(targetFile);
    newFile.encodeName("UTF-8");
    if(!newFile.open(QIODevice::WriteOnly))
    {
        return;
    }
    //将数据取出格式化成xml
    QTextStream inStream(&newFile);

    QString xmlHead = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
    QString strBodyBegin = "<Body useHEX=\"false\"> \r\n";
    QString strBodyEnd = "</Body>";
    //<Msg>

    QString msgLabel = QString(4,space).append(QString("<Msg id =\"%1\" mac =\"%2\" name =\"%3\">\r\n").arg(msgID).arg("true").arg(QString::fromLocal8Bit(tranCodeName.toStdString().data())));
    msgLabel +=QString(8,space).append("<Request>\r\n");
    m_resTagLenMax = m_resTagLenMax + 4;
    QString strTranCode = QString("F_TranCode");
    QString strRequest = QString("head3");
    QString strValue = msgID;
    msgLabel +=QString(12,space).append(QString("<%1").arg(strTranCode))
            .append(QString(fillBlankSpace(strTranCode.length(),m_resTagLenMax),space))
            .append("Request=\"%1\"").arg(strRequest)
            .append(QString(fillBlankSpace(strRequest.length(),m_resTagLenMax),space))
            .append(QString("value=\"%1\"").arg(strValue))
            .append(QString(fillBlankSpace(strValue.length(),m_resTagLenMax),space))
            .append(QString("Remark =\"%1\"/>\r\n").arg(QString::fromLocal8Bit("交易代码")));
                /*QString("   ")
                .arg()
                .arg()
                .arg(msgID)
                .arg();
                */
    qDebug() << " resNum " << m_resNum;

    for(int m=0; m < m_resNum; m++)
    {
        QString strtarName = m_FieldGatherList.at(m).m_strTagName;
        QString strRequest =m_FieldGatherList.at(m).m_strRequestPath;
        QString strValue =m_FieldGatherList.at(m).m_strValue;
        int tagSpace = fillBlankSpace(strtarName.length(),m_resTagLenMax);
        int reqSpace = fillBlankSpace(strRequest.length(),m_resTagLenMax);
        int valSpace = fillBlankSpace(strValue.length(),m_resTagLenMax);

        msgLabel += QString(12,space)
                .append(QString("<%1").arg(strtarName))\
                .append(QString(tagSpace,space))\
                .append(QString("Request=\"%1\"").arg(strRequest))
                .append(QString(reqSpace,space))\
                .append(QString("value=\"%1\"").arg(strValue))\
                .append(QString(valSpace,space))
                .append(QString("Remark =\"%4\"/>\r\n").arg(QString::fromLocal8Bit(m_FieldGatherList.at(m).m_strRemark.toStdString().data())));
                /*QString("<%1 Request=\"%2\" value=\"%3\" Remark =\"%4\"/>\r\n")*/
   }
    msgLabel +=QString(8,space).append("</Request>\r\n");
    qDebug() << "Requst end";
    msgLabel +=QString(8,space).append(QString("<Response>\r\n"));
    m_respTagLenMax = m_respTagLenMax + 4;
    int totalNum = m_FieldGatherList.size();
    for(int k= m_resNum; k < totalNum; k++)
    {
        QString strTarName = m_FieldGatherList.at(k).m_strTagName;
        QString strResponse = m_FieldGatherList.at(k).m_strResponsePath;
        QString strValue = m_FieldGatherList.at(k).m_strValue;
        msgLabel += QString(12,space)
                .append(QString("<%1").arg(strTarName))\
                .append(QString(fillBlankSpace(strTarName.length(),m_respTagLenMax),space))\
                .append(QString("Response=\"%1\"").arg(strResponse))\
                .append(QString(fillBlankSpace(strResponse.length(),m_respTagLenMax),space))\
                .append(QString("value=\"%1\"").arg(strValue))\
                .append(QString(QString(fillBlankSpace(strValue.length(),m_respTagLenMax),space)))
                .append(QString("Remark =\"%1\"/>\r\n""").arg(QString::fromLocal8Bit(m_FieldGatherList.at(k).m_strRemark.toStdString().data())));
                /*QString("<%1    Response=\"%2\"    value=\"%3\"    Remark =\"%4\"/>\r\n")*/
    }
    msgLabel +=QString(8,space).append(QString("</Response>\r\n"));
    msgLabel +=QString(4,space).append(QString("</Msg>\r\n"));
    QString xml = xmlHead + strBodyBegin + msgLabel + strBodyEnd;
        qDebug() << xml;
    inStream << xml; //<< strBodyBegin << msgLabel <<strBodyEnd;
    newFile.close();
    qDebug() << m_FieldGatherList.size();
    for(int i=0; i< m_FieldGatherList.size();i++)
    {
        qDebug() << m_FieldGatherList.at(i).m_strRemark;
        qDebug() << m_FieldGatherList.at(i).m_strTagName;
        qDebug() << m_FieldGatherList.at(i).m_strValue;
        qDebug() << m_FieldGatherList.at(i).m_strRequestPath;
        qDebug() << m_FieldGatherList.at(i).m_strResponsePath;
        qDebug() << "-------------------------------------";

    }








}

int ConfMsg::fillBlankSpace(int arg1, int arg2)
{
    return arg2 -arg1;
}
int ConfMsg::CompareThreeNum(int arg1, int arg2, int m_arg3)
{
    int max =0;
    if(arg1>=arg2)
    {
        if(arg1 >= m_arg3)
        {
            max =arg1;
        }
        else
        {
            max = m_arg3;
        }
    }
    else
    {
        if(arg2 >= m_arg3)
        {
            max = arg2;
        }
        else
        {
            max = m_arg3;
        }
    }
    return max;
}
